import { NextRequest, NextResponse } from "next/server";

/**
 * 通用API代理工具
 */

/**
 * 创建带认证的API代理处理器
 */
export const createAuthProxyHandler = (
  baseUrl: string,
  options: {
    requireAuth?: boolean;
    method?: string;
  } = {}
) => {
  return async (request: NextRequest) => {
    try {
      const { searchParams } = new URL(request.url);
      const method = options.method || request.method;

      // 获取Custom头部
      const customHeader =
        request.headers.get("custom") || request.headers.get("Custom");

      if (options.requireAuth !== false && !customHeader) {
        return NextResponse.json(
          { success: false, message: "Custom header is required" },
          { status: 401 }
        );
      }

      // 构建外部API URL
      const externalUrl = `${baseUrl}?${searchParams.toString()}`;
      console.log(`API代理 - 调用外部API: ${externalUrl}`);

      // 准备请求头
      const headers: Record<string, string> = {
        "Content-Type": "application/json",
      };

      if (customHeader) {
        headers.Custom = customHeader;
      }

      // 调用外部API
      const response = await fetch(externalUrl, {
        method,
        headers,
      });

      console.log(`API代理 - 外部API响应状态: ${response.status}`);

      const data = await response.json();
      console.log(`API代理 - 外部API响应数据:`, data);

      return NextResponse.json(data, { status: response.status });
    } catch (error) {
      console.error("API代理错误:", error);
      return NextResponse.json(
        {
          success: false,
          message: "Internal server error",
          error: error.message,
        },
        { status: 500 }
      );
    }
  };
};

/**
 * 常用的API代理配置
 */
export const API_PROXY_CONFIGS = {
  // 收藏相关
  favorite: {
    baseUrl: "http://admin.insp.test.tz-group.com/proapi/user_center/favorite",
    requireAuth: true,
  },
  favoriteRemove: {
    baseUrl:
      "http://admin.insp.test.tz-group.com/proapi/user_center/favorite/remove",
    requireAuth: true,
  },
  // 小程序码
  wechatCode: {
    baseUrl: "http://admin.insp.test.tz-group.com/proapi/common/wei_xin_code",
    requireAuth: true,
  },
  // OSS配置
  oss: {
    baseUrl: "http://admin.insp.test.tz-group.com/proapi/common/oss",
    requireAuth: true,
  },
  // 认证申请
  application: {
    baseUrl:
      "http://admin.insp.test.tz-group.com/proapi/user_center/application",
    requireAuth: false,
  },
};
